# -*- coding: utf-8 -*-
# @Author: long
# @Date:   2017-12-19 04:39:47
# @Last Modified by:   ystlong
# @Last Modified time: 2017-12-23 08:46:38

import time
import threading
import socket

def clean_socket(sock):
	try:
		sock.shutdown(socket.SHUT_RDWR)
	except Exception as e:
		print(repr(e))
	try:
		sock.close()
	except Exception as e:
		print(repr(e))

def delay(nmsec):
	n = nmsec / 1000
	if n <= 0:
		n = 1
	time.sleep(n)

class HookThreadManager(object):
	"""docstring for HookThreadManager"""
	def __init__(self):
		super(HookThreadManager, self).__init__()
		self.threads = {}
		self.on = True

	def new_thread(self, target):
		key = None
		def run_target():
			target()
			# print("dbg: thread exit")
			del self.threads[key]

		instance = threading.Thread(target=run_target)
		key = str(instance)
		self.threads[key] = instance
		instance.setDaemon(True)
		instance.start()

	def close(self):
		for k in self.threads:
			try:
				self.threads[k].exit(1)
			except Exception as e:
				# raise e
				pass
		self.on = False
		print "thread close"

	def wait(self):
		alive = False
		while self.on:
			# print("dbg: current trheads: %d"%(len(self.threads)))
			for th in self.threads:
				try:
					alive = alive or self.threads[th].isAlive()
				except Exception as e:
					print(repr(e))
				if alive:
					break
			if alive:
				time.sleep(1)
			else:
				break
		print("dbg: exit wait threads")

ProxyThreadPool = HookThreadManager()		
